<template>
  <view class="register-container">
    <view class="register-content">
      <view class="logo-box">
        <image class="logo" src="/static/fishPiLogo.png" mode="aspectFit"></image>
        <text class="title">摸鱼派</text>
        <text class="subtitle">加入摸鱼派，开始您的摸鱼之旅</text>
      </view>

      <!-- 第一步：基本信息和图形验证码 -->
      <view class="form-box" v-if="currentStep === 1">
        <view class="input-group">
          <text class="label">用户名</text>
          <view class="input-wrapper">
            <input class="input" type="text" v-model="formData.userName" placeholder="请输入用户名"
              placeholder-class="placeholder" />
          </view>
          <text class="tips">用户名只能包含字母、数字和下划线</text>
        </view>

        <view class="input-group">
          <text class="label">手机号</text>
          <view class="input-wrapper">
            <input class="input" type="number" maxlength="11" v-model="formData.userPhone" placeholder="请输入手机号"
              placeholder-class="placeholder" />
          </view>
        </view>

        <view class="input-group">
          <text class="label">邀请码 (选填)</text>
          <view class="input-wrapper">
            <input class="input" type="text" v-model="formData.invitecode" placeholder="留空则使用默认邀请码"
              placeholder-class="placeholder" />
          </view>
        </view>

        <view class="input-group verification">
          <text class="label">图形验证码</text>
          <view class="verification-box">
            <view class="input-wrapper captcha-input">
              <input class="input" type="text" v-model="formData.captcha" placeholder="请输入验证码"
                placeholder-class="placeholder" />
            </view>
            <image class="captcha-img" :src="captchaUrl" @click="refreshCaptcha"></image>
          </view>
        </view>

        <view class="agreement">
          <checkbox :checked="formData.agreeTerms" @click="formData.agreeTerms = !formData.agreeTerms" color="#f0d35e">
          </checkbox>
          <text class="agreement-text">我已阅读并同意</text>
          <text class="link" @click="openTerms">《用户协议》</text>
        </view>

        <button class="register-btn" @click="handleGetSmsCode" :disabled="loading">
          {{ loading ? "处理中..." : "获取短信验证码" }}
        </button>

        <view class="action-links">
          <navigator url="/pages/login/login" open-type="redirect" class="login-link">
            已有账号？立即登录
          </navigator>
        </view>
      </view>

      <!-- 第二步：短信验证码 -->
      <view class="form-box" v-if="currentStep === 2">
        <view class="step-title">
          <text>验证手机号</text>
        </view>

        <view class="input-group">
          <text class="label">短信验证码</text>
          <view class="input-wrapper">
            <input class="input" type="number" maxlength="6" v-model="formData.smsCode" placeholder="请输入短信验证码"
              placeholder-class="placeholder" />
          </view>
          <text class="tips">验证码已发送至 {{ formData.userPhone }}</text>
        </view>

        <button class="register-btn" @click="handleVerifySmsCode" :disabled="loading">
          {{ loading ? "验证中..." : "验证" }}
        </button>

        <view class="back-link" @click="currentStep = 1"> 返回上一步 </view>
      </view>

      <!-- 第三步：设置密码和用户角色 -->
      <view class="form-box" v-if="currentStep === 3">
        <view class="step-title">
          <text>完成注册</text>
        </view>

        <view class="input-group">
          <text class="label">密码</text>
          <view class="input-wrapper">
            <input class="input" type="password" v-model="formData.userPassword" placeholder="请输入密码"
              placeholder-class="placeholder" />
          </view>
          <text class="tips">密码长度不少于8位</text>
        </view>

        <view class="input-group">
          <text class="label">确认密码</text>
          <view class="input-wrapper">
            <input class="input" type="password" v-model="formData.confirmPassword" placeholder="请再次输入密码"
              placeholder-class="placeholder" />
          </view>
        </view>

        <view class="role-selection">
          <text class="label">选择角色</text>
          <view class="role-options">
            <view class="role-option" :class="{ active: formData.userAppRole === 0 }" @click="formData.userAppRole = 0">
              <text class="role-name">黑客</text>
            </view>
            <view class="role-option" :class="{ active: formData.userAppRole === 1 }" @click="formData.userAppRole = 1">
              <text class="role-name">画家</text>
            </view>
          </view>
        </view>

        <button class="register-btn" @click="handleCompleteRegister" :disabled="loading">
          {{ loading ? "注册中..." : "完成注册" }}
        </button>

        <view class="back-link" @click="currentStep = 2"> 返回上一步 </view>
      </view>

      <view class="geek-footer" v-if="currentStep === 1">
        <text class="footer-text">/* 代码改变世界 */</text>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive } from "vue";
  import api from "@/api";
  import {
    showLoading,
    hideLoading,
    showError,
    showSuccess,
    md5,
  } from "@/utils/common.js";

  // 当前注册步骤
  const currentStep = ref(1);

  // 表单数据
  const formData = reactive({
    // 第一步
    userName: "",
    userPhone: "",
    invitecode: "",
    captcha: "",
    agreeTerms: false,

    // 第二步
    smsCode: "",
    userId: "", // 存储第二步返回的userId

    // 第三步
    userPassword: "",
    confirmPassword: "",
    userAppRole: 0, // 默认选择黑客角色
  });

  const loading = ref(false);
  const captchaUrl = ref("https://fishpi.cn/captcha");

  // 刷新验证码
  const refreshCaptcha = () => {
    captchaUrl.value = `https://fishpi.cn/captcha?timestamp=${Date.now()}`;
  };

  // 打开用户协议
  const openTerms = () => {
    uni.navigateTo({
      url:
        "/pages/webview/webview?url=" +
        encodeURIComponent("https://fishpi.cn/agreement"),
    });
  };

  // 验证第一步表单
  const validateStepOne = () => {
    if (!formData.userName) {
      showError("请输入用户名");
      return false;
    }

    if (!/^[a-zA-Z0-9_]+$/.test(formData.userName)) {
      showError("用户名只能包含字母、数字和下划线");
      return false;
    }

    if (!formData.userPhone) {
      showError("请输入手机号");
      return false;
    }

    if (!/^1\d{10}$/.test(formData.userPhone)) {
      showError("请输入正确的手机号格式");
      return false;
    }

    if (!formData.captcha) {
      showError("请输入图形验证码");
      return false;
    }

    if (!formData.agreeTerms) {
      showError("请阅读并同意用户协议");
      return false;
    }

    return true;
  };

  // 验证第二步表单
  const validateStepTwo = () => {
    if (!formData.smsCode) {
      showError("请输入短信验证码");
      return false;
    }

    if (!/^\d{6}$/.test(formData.smsCode)) {
      showError("请输入正确的短信验证码格式");
      return false;
    }

    return true;
  };

  // 验证第三步表单
  const validateStepThree = () => {
    if (!formData.userPassword) {
      showError("请输入密码");
      return false;
    }

    if (formData.userPassword.length < 8) {
      showError("密码长度不能少于8位");
      return false;
    }

    if (formData.userPassword !== formData.confirmPassword) {
      showError("两次输入的密码不一致");
      return false;
    }

    return true;
  };

  // 第一步：获取短信验证码
  const handleGetSmsCode = async () => {
    if (!validateStepOne()) {
      return;
    }

    try {
      loading.value = true;
      showLoading("获取验证码中");

      // 调用注册API获取短信验证码
      const res = await api.user.register({
        userName: formData.userName,
        userPhone: formData.userPhone,
        invitecode: formData.invitecode || "otis1026",
        captcha: formData.captcha,
      });

      // 成功
      if (res.code === 0) {
        showSuccess("短信验证码已发送");
        currentStep.value = 2; // 进入第二步
      } else {
        showError(res.msg || "获取短信验证码失败");
        // 刷新验证码
        refreshCaptcha();
      }
    } catch (error) {
      showError(error.message || "获取短信验证码失败，请稍后再试");
      // 刷新验证码
      refreshCaptcha();
    } finally {
      loading.value = false;
      hideLoading();
    }
  };

  // 第二步：验证短信验证码
  const handleVerifySmsCode = async () => {
    if (!validateStepTwo()) {
      return;
    }

    try {
      loading.value = true;
      showLoading("验证中");

      // 调用验证短信验证码API
      const res = await api.user.verifySmsCode(formData.smsCode);

      // 验证成功
      if (res.code === 0) {
        formData.userId = res.userId; // 保存返回的userId
        showSuccess("验证成功");
        currentStep.value = 3; // 进入第三步
      } else {
        showError(res.msg || "短信验证码验证失败");
      }
    } catch (error) {
      showError(error.message || "短信验证码验证失败，请稍后再试");
    } finally {
      loading.value = false;
      hideLoading();
    }
  };

  // 第三步：完成注册
  const handleCompleteRegister = async () => {
    if (!validateStepThree()) {
      return;
    }

    try {
      loading.value = true;
      showLoading("注册中");

      // MD5加密密码
      const md5Password = md5(formData.userPassword);

      // 调用完成注册API
      const res = await api.user.completeRegister(
        {
          userAppRole: formData.userAppRole,
          userPassword: md5Password,
          userId: formData.userId,
        },
        formData.invitecode || "otis1026"
      ); // 如果用户未填写邀请码，则使用默认邀请码otis1026

      // 注册成功
      if (res.code === 0) {
        showSuccess("注册成功");

        // 跳转到登录页
        setTimeout(() => {
          uni.redirectTo({
            url: "/pages/login/login",
          });
        }, 1500);
      } else {
        showError(res.msg || "注册失败");
      }
    } catch (error) {
      showError(error.message || "注册失败，请稍后再试");
    } finally {
      loading.value = false;
      hideLoading();
    }
  };

  // 页面加载时刷新验证码
  refreshCaptcha();
</script>

<style lang="scss">
  .register-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #121212;
    background-image: radial-gradient(circle at 15% 50%,
        rgba(36, 36, 36, 0.5) 0%,
        transparent 20%),
      radial-gradient(circle at 85% 30%,
        rgba(36, 36, 36, 0.5) 0%,
        transparent 20%);
  }

  .register-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 85%;
    padding: 80rpx 0;
  }

  .logo-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 60rpx;

    .logo {
      width: 160rpx;
      height: 160rpx;
      margin-bottom: 30rpx;
    }

    .title {
      font-size: 52rpx;
      font-weight: bold;
      color: #ffffff;
      margin-bottom: 10rpx;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }

    .subtitle {
      font-size: 28rpx;
      color: #f0d35e;
      letter-spacing: 2rpx;
    }
  }

  .form-box {
    width: 100%;
    background-color: rgba(30, 30, 30, 0.8);
    border-radius: 16rpx;
    padding: 50rpx 40rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);

    .step-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #ffffff;
      margin-bottom: 40rpx;
      text-align: center;
    }

    .input-group {
      margin-bottom: 40rpx;

      .label {
        display: block;
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.8);
        margin-bottom: 16rpx;
        font-family: "Menlo", "Monaco", monospace;
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        transition: border 0.3s ease;
        padding-bottom: 10rpx;

        &:focus-within {
          border-bottom: 1px solid #f0d35e;
        }
      }

      .input {
        flex: 1;
        height: 80rpx;
        font-size: 32rpx;
        color: #ffffff;
        background: transparent;
        font-family: "Menlo", "Monaco", monospace;
      }

      .placeholder {
        color: rgba(255, 255, 255, 0.4);
      }

      .tips {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.6);
        margin-top: 8rpx;
      }
    }

    .verification {
      .verification-box {
        display: flex;
        align-items: center;

        .captcha-input {
          flex: 1;
        }

        .captcha-img {
          width: 200rpx;
          height: 80rpx;
          margin-left: 20rpx;
          border-radius: 4rpx;
        }
      }
    }

    .role-selection {
      margin-bottom: 30rpx;

      .label {
        display: block;
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.8);
        margin-bottom: 16rpx;
        font-family: "Menlo", "Monaco", monospace;
      }

      .role-options {
        display: flex;
        justify-content: space-between;

        .role-option {
          width: 48%;
          height: 120rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 8rpx;

          &.active {
            background-color: rgba(240, 211, 94, 0.1);
            border-color: #f0d35e;
          }

          .role-name {
            font-size: 32rpx;
            color: #ffffff;
          }
        }
      }
    }

    .agreement {
      display: flex;
      align-items: center;
      margin: 30rpx 0;

      .agreement-text {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.7);
        margin-left: 10rpx;
      }

      .link {
        font-size: 28rpx;
        color: #f0d35e;
      }
    }

    .register-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      background-color: #f0d35e;
      color: #121212;
      font-size: 32rpx;
      font-weight: bold;
      border-radius: 8rpx;
      margin-top: 30rpx;
      letter-spacing: 2rpx;
      box-shadow: 0 4rpx 12rpx rgba(240, 211, 94, 0.3);
      transition: all 0.3s ease;

      &:after {
        border: none;
      }

      &:active {
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 6rpx rgba(240, 211, 94, 0.2);
      }

      &[disabled] {
        background-color: rgba(240, 211, 94, 0.5);
        color: rgba(18, 18, 18, 0.7);
      }
    }

    .action-links {
      display: flex;
      justify-content: center;
      margin-top: 40rpx;
      font-size: 26rpx;

      .login-link {
        color: #f0d35e;
        text-decoration: none;
      }
    }

    .back-link {
      text-align: center;
      margin-top: 30rpx;
      color: #f0d35e;
      font-size: 26rpx;
    }
  }

  .geek-footer {
    margin-top: 60rpx;
    text-align: center;

    .footer-text {
      font-family: "Menlo", "Monaco", monospace;
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.5);
    }
  }
</style>